package net.wofly.sale.stock.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.web.BaseController;
import net.wofly.framework.util.ReturnBean;
import net.wofly.sale.stock.domain.ResourceAsk;
import net.wofly.sale.stock.dto.ResourceAskStatusDTO;
import net.wofly.sale.stock.flow.IResourceAskFlowService;
import net.wofly.sale.stock.service.IResourceAskService;
import net.wofly.sale.stock.validator.ResourceAskValidator;

/**
 * Created by LiuJianbo on 2017/10/9.
 */
@Controller
@RequestMapping(value = "/api/resourceAsk")
@Api(description = "领料接口")
public class ResourceAskController extends BaseController {

    private static final String SESSION_ATTRIBUTE_NAME_USERID = "userID";
    private static final String DEFAULT_PAGE_NUM = "1";
    private static final String DEFAULT_PAGE_SIZE = "10";

    @Resource
    IResourceAskService iResourceAskService;
    @Resource
    IResourceAskFlowService iResourceAskFlowService ;

    /**
     * 领料申请审核
     * <ul>
     * <li>判断当前用户是否有权限进行审核</li>
     * <li></li>
     * </ul>
     *
     * @param resourceAskID
     */
    @ApiOperation(value = "领料申请审核", notes = "领料申请审核")
    @ApiImplicitParams({@ApiImplicitParam(name = "resourceAskID", value = "领料申请ID", required = true, dataType =
            "String", paramType = "form"), @ApiImplicitParam(name = "checkStatus", value = "审核状态", required = true, dataType = "Integer", paramType = "form")})
    @RequestMapping(value = "/checkResourceAsk", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> checkResourceAsk(String resourceAskID, Integer checkStatus, HttpServletRequest request) {
        ReturnBean<String> returnBean;
        String errorMessage = ResourceAskValidator.validateCheckResourceAskParams(resourceAskID, checkStatus);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<String>(1, errorMessage);
        } else {
            String userID = (String) request.getSession().getAttribute(SESSION_ATTRIBUTE_NAME_USERID);
            returnBean = iResourceAskService.checkResourceAsk(resourceAskID, checkStatus, userID);
        }
        return returnBean;
    }

    /**
     * 提交领料申请进行审核
     *
     * @param resourceAskID
     */
    @ApiOperation(value = "提交领料申请进行审核", notes = "提交领料申请进行审核")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "resourceAskID", value = "领料申请ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/commitResourceAsk", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> commitResourceAsk(String resourceAskID, HttpServletRequest request) {
        ReturnBean<String> returnBean;
        String errorMessage = ResourceAskValidator.validateResourceAskID(resourceAskID);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<String>(1, errorMessage);
        } else {
            String userID = (String) request.getSession().getAttribute(SESSION_ATTRIBUTE_NAME_USERID);
            returnBean = iResourceAskService.commitResourceAsk(resourceAskID, userID);
        }
        return returnBean;
    }

    /**
     * @param resourceAskID
     */
    @ApiOperation(value = "发货", notes = "发货")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "resourceAskID", value = "领料申请ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/consign", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> consign(String resourceAskID, HttpServletRequest request) {
        ReturnBean<String> returnBean;
        String errorMessage = ResourceAskValidator.validateResourceAskID(resourceAskID);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<String>(1, errorMessage);
        } else {
            String userID = (String) request.getSession().getAttribute(SESSION_ATTRIBUTE_NAME_USERID);
            returnBean = iResourceAskService.consign(resourceAskID, userID);
        }
        return returnBean;
    }

    /**
     * 删除领料申请
     * <ul>
     * <li>一旦提交不可删除</li>
     * <li></li>
     * </ul>
     *
     * @param resourceAskID
     */
    @ApiOperation(value = "删除领料申请", notes = "删除领料申请")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "resourceAskID", value = "领料申请ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/delResourceAsk", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> delResourceAsk(String resourceAskID,String userID) {
        ReturnBean<String> returnBean;
        String errorMessage = ResourceAskValidator.validateStartWF(userID,resourceAskID);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<String>(1, errorMessage);
        } else {
            returnBean = iResourceAskService.delResourceAsk(resourceAskID ,userID);
        }
        return returnBean;
    }

    /**
     * 领料出库
     * <ul>
     * <li>判断当前用户是否有限制进行出库</li>
     * <li>从出库人所在仓库中减去出库商品数量，并记录出库流水</li>
     * <li>加到申请人所在的入库商品数量，并记录入库流水</li>
     * <li></li>
     * </ul>
     *
     * @param resourceAskID
     */
    @ApiOperation(value = "领料出库", notes = "领料出库")
    @ApiImplicitParams({@ApiImplicitParam(name = "resourceAskID", value = "领料申请ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/outStock", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> outStock(String resourceAskID) {
        ReturnBean<String> returnBean;
        String errorMessage = ResourceAskValidator.validateResourceAskID(resourceAskID);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<String>(1, errorMessage);
        } else {
            returnBean = iResourceAskService.outStock(resourceAskID);
        }
        return returnBean;
    }

    /**
     * 打印发货单
     *
     * @param resourceAskID
     */
    public ReturnBean<ResourceAsk> printConsign(String resourceAskID) {
        return null;
    }

    /**
     * 保存领料申请
     *
     * @param resourceAsk
     */
    @ApiOperation(value = "保存领料申请", notes = "保存领料申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resourceAsk", value = "领料申请实体", required = true, dataType = "ResourceAsk", dataTypeClass = ResourceAsk.class)
    })
    @RequestMapping(value = "/saveResourceAsk", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<ResourceAsk> saveResourceAsk(@RequestBody ResourceAsk resourceAsk) {
        ReturnBean<ResourceAsk> returnBean;
        String errorMessage = ResourceAskValidator.validateSaveResourceAskParams(resourceAsk.getResourceAskLists(), resourceAsk.getAsker());
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<>(1, errorMessage);
        } else {
            returnBean = iResourceAskService.saveResourceAsk(resourceAsk.getResourceAskID() ,resourceAsk.getResourceAskLists(), resourceAsk.getAsker());
        }
        return returnBean;
    }

    /**
     * 更新领料申请
     *
     * @param resourceAsk
     */
    @ApiOperation(value = "更新领料申请", notes = "更新领料申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resourceAsk", value = "领料申请实体", required = true, dataType = "ResourceAsk", dataTypeClass = ResourceAsk.class)
    })
    @RequestMapping(value = "/updateResourceAsk", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<ResourceAsk> updateResourceAsk(@RequestBody ResourceAsk resourceAsk) {
        ReturnBean<ResourceAsk> returnBean;
        //String errorMessage = ResourceAskValidator.validateSaveResourceAskParams(resourceAskLists, asker);
        String errorMessage = null;
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<>(1, errorMessage);
        } else {
            returnBean = iResourceAskService.updateResourceAsk(resourceAsk);
        }
        return returnBean;
    }

    /**
     * 领料申请单详情
     *
     * @param resourceAskID
     */
    @ApiOperation(value = "领料申请单详情", notes = "领料申请单详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "resourceAskID", value = "领料申请ID", required = true, dataType = "String", paramType = "query")})
    @RequestMapping(value = "/getResourceAsk", method = {RequestMethod.GET})
    @ResponseBody
    public ReturnBean<ResourceAsk> getResourceAsk(String resourceAskID){
        ReturnBean<ResourceAsk> returnBean;
        String errorMessage = ResourceAskValidator.validateGetResourceAskParams(resourceAskID);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iResourceAskService.getResourceAsk(resourceAskID);
        }
        return returnBean;
    }

    /**
     * 获取领料申请单
     * <ol>
     * 	<li> askStatus=-1时，表示取所有状态的申请单</li>
     * </ol>
     *
     * @param askNO
     * @param askUserID
     * @param askStatus
     * @param pageNum
     * @param pageSize
     */
    @ApiOperation(value = "获取领料申请单", notes = "获取领料申请单")
    @ApiImplicitParams({@ApiImplicitParam(name = "askNO", value = "申请编码", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "askUserID", value = "申请人ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "askStatus", value = "单据状态", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码（默认第一页）", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数（默认10条）", required = false, dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/getResourceAskList", method = {RequestMethod.GET})
    @ResponseBody
    public ReturnBean<PageWrapper<ResourceAsk>> getResourceAskList(String askNO, String askUserID, Integer askStatus,
                                                                   @RequestParam(defaultValue = DEFAULT_PAGE_NUM) Integer pageNum,
                                                                   @RequestParam(defaultValue = DEFAULT_PAGE_SIZE) Integer pageSize){
        ReturnBean<PageWrapper<ResourceAsk>> returnBean;
        String errorMessage = ResourceAskValidator.validateGetResourceAskListParams(askNO, askUserID, askStatus);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<>(1, errorMessage);
        } else {
            returnBean = iResourceAskService.getResourceAskList(askNO, askUserID, askStatus, pageNum, pageSize);
        }
        return returnBean;
    }

    @ApiOperation(value = "获取资源申请状态列表", notes = "获取资源申请状态列表")
    @RequestMapping(value = "/getResourceAskStatus", method = {RequestMethod.GET})
    @ResponseBody
    public ReturnBean<List<ResourceAskStatusDTO>> getResourceAskStatus(){
        return iResourceAskService.getResourceAskStatus();
    }
    
    @ApiOperation(value = "发起资源申请工作流", notes = "发起资源申请工作流")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "申请人ID", required = true, dataType = "String", paramType = "form") ,
    						@ApiImplicitParam(name = "resourceAskID", value = "领料申请单ID", required = true, dataType = "String", paramType = "form")
    		})
    @RequestMapping(value = "/startWorkflow", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> startWorkflow(HttpServletRequest request ,String userId ,String resourceAskID) {
    		Map<String, Object> variables = new HashMap<>() ;
    		
    		String errorMessage = ResourceAskValidator.validateStartWF(userId,resourceAskID);
    		if (StringUtils.isNotEmpty(errorMessage)) {
                return new ReturnBean<>(1, errorMessage);
    		}
    		
		return iResourceAskService.startWorkflow(userId ,resourceAskID, variables) ;
    }
	
    @ApiOperation(value = "获取资源申请待办", notes = "获取资源申请待办")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "申请人ID", required = true, dataType = "String", paramType = "form")
    		})
    @RequestMapping(value = "/findToDoList", method = {RequestMethod.POST})
    @ResponseBody
	public ReturnBean<List<ResourceAsk>> findToDoList(String userId) {
		
    		List<ResourceAsk> ras = iResourceAskService.findToDoList(userId) ;
		
		return new ReturnBean<>(0,"获取资源申请待办任务成功！" , ras) ;
		
	}
	
    @ApiOperation(value = "完成资源申请工作流任务", notes = "完成资源申请工作流任务")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "申请人ID", required = true, dataType = "String", paramType = "form"),
    						@ApiImplicitParam(name = "taskID", value = "任务ID", required = true, dataType = "String", paramType = "form")
    		})
    @RequestMapping(value = "/complete", method = {RequestMethod.POST})
    @ResponseBody
	public ReturnBean<String> complete(HttpServletRequest request ,String userID ,String taskID) {
    	
		Map<String, String[]> mapRequest = request.getParameterMap() ;
		
		return iResourceAskFlowService.complete(userID, taskID, mapRequest) ;
	}
	
    @ApiOperation(value = "为工作流获取资源申请详情", notes = "为工作流获取资源申请详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "resourceAskID", value = "资源申请ID", required = true, dataType = "String", paramType = "form")
    		})
    @RequestMapping(value = "/getResourceAskForFlow", method = {RequestMethod.POST})
    @ResponseBody
	public ReturnBean<ResourceAsk> getResourceAskForFlow(String resourceAskID) {
		return iResourceAskService.getResourceAskForFlow(resourceAskID) ;
	}
    
    @ApiOperation(value = "向草稿领料申请中增加终端商品", notes = "向草稿领料申请中增加终端商")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "用户ID", required = true, dataType = "String", paramType = "form"),
    						@ApiImplicitParam(name = "commodityTerminalID", value = "终端商品ID", required = true, dataType = "String", paramType = "form"),
    						@ApiImplicitParam(name = "askNum", value = "终端商品数量", required = true, dataType = "Integer", paramType = "form")
    		})
    @RequestMapping(value = "/addResourceAskDraft", method = {RequestMethod.POST})
    @ResponseBody
	public ReturnBean<ResourceAsk> addResourceAskDraft(String userID ,String commodityTerminalID ,Integer askNum) {
    		String errorMessage = ResourceAskValidator.validateAddResourceAsk(userID,commodityTerminalID ,askNum);
		if (StringUtils.isNotEmpty(errorMessage)) {
            return new ReturnBean<>(1, errorMessage);
		}
		
		return iResourceAskService.addResourceAskDraft(userID,commodityTerminalID ,askNum) ;
	}
    
    @ApiOperation(value = "获取领料申请草稿", notes = "获取领料申请草稿")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "用户ID", required = true, dataType = "String", paramType = "form")
    		})
    @RequestMapping(value = "/getResourceAskDraft", method = {RequestMethod.POST})
    @ResponseBody
	public ReturnBean<ResourceAsk> getResourceAskDraft(String userID) {
    		StringBuffer stringBuffer = new StringBuffer();
    		ResourceAskValidator.validateUserID(stringBuffer, userID);
		if (StringUtils.isNotEmpty(stringBuffer.toString())) {
            return new ReturnBean<>(1, stringBuffer.toString());
		}
		
		return iResourceAskService.getResourceAskDraft(userID) ;
	}
    
    @ApiOperation(value = "获取领料申请草稿", notes = "获取领料申请草稿")
    @ApiImplicitParams({@ApiImplicitParam(name = "resourceAskListID", value = "用户ID", required = true, dataType = "String", paramType = "form")
    		})
    @RequestMapping(value = "/delResourceAskList", method = {RequestMethod.POST})
    @ResponseBody
	public ReturnBean<String> delResourceAskList(String resourceAskListID) {
    		String errorMessage = ResourceAskValidator.validateResourceAskListID(resourceAskListID);
		if (StringUtils.isNotEmpty(errorMessage)) {
            return new ReturnBean<>(1, errorMessage);
		}
		
		return iResourceAskService.delResourceAskList(resourceAskListID) ;
	}
	
}
